package com.yltrcc.blog.controller.api;

import com.yltrcc.blog.generate.domain.QbCategory;
import com.yltrcc.blog.generate.mapper.QbCategoryMapper;
import com.yltrcc.blog.generate.service.QbCategoryService;
import com.yltrcc.blog.model.model.BaseApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 企业微信 群推送APi
 */
@RestController
@RequestMapping(value = "/api/category")
public class QbCategoryApiController {

    @Autowired
    private QbCategoryService qbCategoryService;

    @Resource
    private QbCategoryMapper qbCategoryMapper;

    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public BaseApiResponse save(@RequestParam(value = "categoryName", defaultValue = "") String categoryName,
                                @RequestParam(value = "upperId", defaultValue = "0") Integer upperId ) {

        if (!StringUtils.hasText(categoryName) || upperId==0) {
            return new BaseApiResponse();
        }
       try {
           //正常 回收站
           QbCategory qbCategory = new QbCategory();
           qbCategory.setCategoryName(categoryName);
           qbCategory.setCategoryDescribe(categoryName);
           qbCategory.setUpperCategoryId(upperId);
           qbCategoryService.save(qbCategory);
       }catch (DuplicateKeyException e) {
           return new BaseApiResponse(500, 500, "不可保存相同内容！！！");
       }catch (Exception e) {
           return new BaseApiResponse(500, 500, "未知异常，请联系管理员！！！");
       }

        return new BaseApiResponse();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/updateContent")
    public BaseApiResponse updateContent(@RequestParam(value = "categoryId", defaultValue = "0") Integer categoryId,
                                @RequestParam(value = "categoryName", defaultValue = "") String categoryName ) {

        if (!StringUtils.hasText(categoryName) || categoryId==0) {
            return new BaseApiResponse();
        }
        try {
            QbCategory qbCategory = qbCategoryService.getById(categoryId);
            qbCategory.setCategoryName(categoryName);
            qbCategory.setCategoryDescribe(categoryName);

            qbCategoryMapper.updateById(qbCategory);

        }catch (Exception e) {
            return new BaseApiResponse(500, 500, "未知异常，请联系管理员！！！");
        }

        return new BaseApiResponse();
    }
}
